import {
  Controller,
  Post,
  Body,
  BadRequestException,
  Req,
  Response,
  Get,
} from '@nestjs/common';
import { ApiBody, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { AuthService } from './auth.service';
import { LoginDto } from './dto/login.dto';

@Controller('auth')
@ApiTags('身份验证')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Post('login')
  @ApiOperation({
    summary: '帐号登录',
    description: '根据帐号和密码登录',
  })
  @ApiBody({ type: LoginDto })
  @ApiResponse({ status: 200, description: '帐号登录成功' })
  async login(@Body() loginDto: LoginDto) {
    const user = await this.authService.validateUser(
      loginDto.account,
      loginDto.password,
    );

    if (!user) {
      throw new BadRequestException('帐号或密码不存在');
    }

    try {
      return await this.authService.login(user);
    } catch (err) {
      throw new BadRequestException('登录失败');
    }
  }

  @Post('logout')
  @ApiOperation({
    summary: '帐号登出',
    description: '帐号登出',
  })
  @ApiResponse({ status: 200, description: '帐号登出成功' })
  logout(@Req() req, @Response() res): void {
    // 清除cookie中的jwt
    res.cookie('jwt', '', { httpOnly: true, expires: new Date(0) });
    // 如果是localStorage存的token需要前端自己删除
    res.status(200).send({
      code: 200,
      msg: 'success',
      result: { message: '登出成功' },
    });
  }

  @Get('queryCurrentUser')
  @ApiOperation({
    summary: '查询当前账户信息',
    description: '通过token查询当前登录账户信息',
  })
  @ApiResponse({ status: 200, description: '账户信息查询成功' })
  queryCurrentUser(@Req() req) {
    return this.authService.queryCurrentUser(req);
  }
}
